package com.alan.springbootwp.service.impl;

import com.alan.springbootwp.service.ClickTypeService;
import com.alan.springbootwp.service.MessageService;
import com.alan.springbootwp.util.MessageUtil;
import com.alan.springbootwp.util.WeChatConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author Alan
 * @Description
 * @date 2020年03月31日 14:19
 */
@Service
public class MessageServiceImpl implements MessageService {


    @Autowired
    private ClickTypeService clickTypeService;

    @Override
    public String handleMessage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, String> map = MessageUtil.parseXml(request);

        String msgType = map.get("MsgType");
        String result = "";

        if (WeChatConstant.MESSAGE_TYPE_TEXT.equals(msgType)) {
            // 文本类型
            result = handleText(map, request, response);
        } else if (WeChatConstant.MESSAGE_TYPE_EVENT.equals(msgType)) {
            // 事件类型
            result = handleEvent(map, request, response);
        } else if (WeChatConstant.MESSAGE_TYPE_IMAGE.equals(msgType)) {
            // 图片类型
            result = "您好，本公众号暂不支持图片消息,请用文字描述你所要咨询的问题！";
        } else if (WeChatConstant.MESSAGE_TYPE_VIDEO.equals(msgType)) {
            // 视频类型
            result = "您好，本公众号暂不支持视频消息,请用文字描述你所要咨询的问题！";
        } else if (WeChatConstant.MESSAGE_TYPE_VOICE.equals(msgType)) {
            // 语音类型
            result = "您好，本公众号暂不支持语音消息,请用文字描述你所要咨询的问题！";
        } else if (WeChatConstant.MESSAGE_TYPE_SHORTVIDEO.equals(msgType)) {
            // 短视频类型
            result = "您好，本公众号暂不支持短视频消息,请用文字描述你所要咨询的问题！";
        } else if (WeChatConstant.MESSAGE_TYPE_LOCATION.equals(msgType)) {
            // 地理位置类型
            result = "您好，本公众号暂不支持位置消息,请用文字描述你所要咨询的问题！";
        } else if (WeChatConstant.MESSAGE_TYPE_LINK.equals(msgType)) {
            // 链接类型
            result = "您好，本公众号暂不支持链接消息,请用文字描述你所要咨询的问题！";
        } else {
            result = handleText(map, request, response);
        }
        return result;
    }

    /**
     * 处理文本类型
     * @param map
     * @param request
     * @param response
     * @return
     */
    private String handleText(Map<String, String> map, HttpServletRequest request, HttpServletResponse response) {
        String result = "请求成功";
        String requestContent = map.get("Content");

        if ((requestContent.indexOf(WeChatConstant.SYMBOL_BIND) == 0) && (requestContent.indexOf(WeChatConstant.SYMBOL_SEPARATOR) > -1)) {
            // 绑定账号：@开头且包含/   @账号/密码
            result = bindAccount(map);
        } else if ((requestContent.indexOf(WeChatConstant.SYMBOL_UNBIND) == 0) && (requestContent.indexOf(WeChatConstant.SYMBOL_SEPARATOR) > -1)) {
            // 解绑账号：#开头且包含/   #账号/密码
            result = unbindAccount(map);
        } else {
            result = "Hello "+requestContent+"；openId："+map.get("FromUserName");
        }

        return MessageUtil.buildTextMessage(map, result);
    }


    /**
     * 处理事件类型
     * 1 关注/取消关注事件
     * 2 扫描带参数二维码事件
     * 3 上报地理位置事件
     * 4 自定义菜单事件
     * 5 点击菜单拉取消息时的事件推送
     * 6 点击菜单跳转链接时的事件推送
     * @param map
     * @param request
     * @param response
     * @return
     */
    private String handleEvent(Map<String, String> map, HttpServletRequest request, HttpServletResponse response) {
        String eventType = map.get("Event");
        String content = "";
        if (WeChatConstant.EVENT_TYPE_CLICK.equals(eventType)) {
            // 点击事件类型
            String eventKey = map.get("EventKey");

            //事件处理
            clickTypeService.clickService(map,eventKey);

            content = "Hello WeChat"+"---eventKey:"+eventKey;
            return MessageUtil.buildTextMessage(map, content);

        } else if (WeChatConstant.EVENT_TYPE_SUBSCRIBE.equals(eventType)) {
            // 订阅
            content = "欢迎关注，" + WeChatConstant.PLATFORM_NAME;
            return MessageUtil.buildTextMessage(map, content);
        } else if (WeChatConstant.EVENT_TYPE_UNSUBSCRIBE.equals(eventType)) {
            // 取消订阅
            content = "取消关注";
            return MessageUtil.buildTextMessage(map, content);
        }

        return MessageUtil.buildTextMessage(map, content);
    }


    /**
     * 解绑账号
     * @param map
     * @return
     */
    private String unbindAccount(Map<String, String> map) {
        String msg = "解绑成功";

        // 发送方帐号（open_id）
        String openId = map.get("FromUserName");

        // 请求内容
        String requestContent = map.get("Content").trim();

        int separatorIndex = requestContent.indexOf(WeChatConstant.SYMBOL_SEPARATOR);
        String userAccount = requestContent.substring(1, separatorIndex);
        String password = requestContent.substring(separatorIndex + 1);

        // 判断账号密码是否正确


        return msg+"账号："+userAccount+"；密码："+password+"；openId："+openId;
    }

    /**
     * 绑定账号
     * @param map
     * @return
     */
    private String bindAccount(Map<String, String> map) {
        String msg = "绑定成功";

        // 发送方帐号（open_id）
        String openId = map.get("FromUserName");

        // 请求内容
        String requestContent = map.get("Content").trim();

        int separatorIndex = requestContent.indexOf(WeChatConstant.SYMBOL_SEPARATOR);
        String userAccount = requestContent.substring(1, separatorIndex);
        String password = requestContent.substring(separatorIndex + 1);

        // 判断账号密码是否正确

        return msg+"账号："+userAccount+"；密码："+password+"；openId："+openId;
    }

    @Override
    public String emoji(int hexEmoji) {
        return String.valueOf(Character.toChars(hexEmoji));
    }

    @Override
    public void responseStr(HttpServletResponse response, String result) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setHeader("cache-control", "no-cache");
        response.setHeader("pragma", "no-cache");
        response.setDateHeader("expires", 0L);

        response.getWriter().write(result);
        response.getWriter().flush();
        response.getWriter().close();

    }
}
